package com.foreveross.utils.crypt;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import com.foreveross.chameleonsdk.config.CubeConstants;
import com.foreveross.chameleonsdk.config.URL;

import java.io.*;

/**
 * description: 自定义的ContentProvider，用于处理WebView的资源加载请求,并根据url进行鉴别处理。
 *
 * @date: 2014年5月8日
 * @author: wzq
 */
public class WebFileProvider extends ContentProvider {
    //public static final String MODULE_ROOT_IN_SD = CubeConstants.SD_ROOT + "/com.foreveross.chameleon/www";
    public static final String MODULE_ROOT_IN_SD = "/mnt/sdcard/com.foreveross.chameleon/www";
    public static final String BASE_URL = URL.SCHEME_PROVIDER + MODULE_ROOT_IN_SD + "/";
    private static final String ENCODING_UTF8 = "utf8";

    private static final String TAG = WebFileProvider.class.getSimpleName();
    @Override
    public ParcelFileDescriptor openFile(Uri uri, String mode) {
        //Log.v(TAG, "fetching:uri = " + uri);
        final String uriPath = uri.getPath();
        String fullPath = getFullPath(uri.getPath());
        //Log.v(TAG, "fullPath = " + fullPath);
        File file = new File(fullPath);
        if(file.isDirectory()) {
            //Log.e(TAG, "file id dir =" + file.getAbsolutePath());
            return null;
        }
        ParcelFileDescriptor parcel = null;
        try {
            InputStream resultStream = AesTool.getFileAsStream(fullPath, ENCODING_UTF8);
            // check result
            if(resultStream != null) {
                parcel = ParcelFileDescriptorUtil.pipeFrom(resultStream);
            }
        } catch(FileNotFoundException e) {
            Log.e(TAG, "file not found : uri=" + uri);
        } catch(IOException e) {
            Log.e(TAG, "Stream to ParcelFileDescriptor error " + e.toString());
        }
        if(parcel == null) {
            Log.e(TAG, "null result at:" + uriPath);
        }
        return parcel;
    }

    @Override
    public boolean onCreate() {
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        throw new UnsupportedOperationException("Not supported by this provider");
    }

    @Override
    public String getType(Uri uri) {
        throw new UnsupportedOperationException("Not supported by this provider");
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        throw new UnsupportedOperationException("Not supported by this provider");
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        throw new UnsupportedOperationException("Not supported by this provider");
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        throw new UnsupportedOperationException("Not supported by this provider");
    }

    /**
     * 获取文件完整路径，如果不是以sd开头，说明是相对根目录的路径
     *
     * @param filePath
     *
     * @return 完整路径 /mnt/sdcard/.../myfile.xx
     */
    private static String getFullPath(String filePath) {
        String path = filePath;
        if(!filePath.startsWith(WebFileProvider.MODULE_ROOT_IN_SD)) {
            path = WebFileProvider.MODULE_ROOT_IN_SD + filePath;
        }
        return path;
    }

    static class ParcelFileDescriptorUtil {
        public static ParcelFileDescriptor pipeFrom(InputStream inputStream) throws IOException {
            ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe();
            ParcelFileDescriptor readSide = pipe[0];
            ParcelFileDescriptor writeSide = pipe[1];
            // start the transfer thread
            new TransferThread(inputStream, new ParcelFileDescriptor.AutoCloseOutputStream(writeSide)).start();
            return readSide;
        }

        static class TransferThread extends Thread {
            final InputStream mIn;
            final OutputStream mOut;

            TransferThread(InputStream in, OutputStream out) {
                super("ParcelFileDescriptor Transfer Thread");
                mIn = in;
                mOut = out;
                setDaemon(true);
            }

            @Override
            public void run() {
                byte[] buf = new byte[1024];
                int len;
                try {
                    while((len = mIn.read(buf)) > 0) {
                        mOut.write(buf, 0, len);
                    }
                    mOut.flush(); // just to be safe
                } catch(IOException e) {
                    Log.e(TAG, "TransferThread " + e.toString());
                } finally {
                    try {
                        mIn.close();
                    } catch(IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        mOut.close();
                    } catch(IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}
